package tx面试;

import java.util.concurrent.Semaphore;

// 交替打印   1 A  2 B 3 C 这样的线程
public class alternatingPrinter {

    public static Semaphore  text = new Semaphore(1);
    public  static  Semaphore  word=new Semaphore(0);

    public static   int maxText=10;
    public static  int maxWord='C';
    public  static  boolean isText=false;
    public  static  boolean isWord=false;
    public static void main(String[] args) {

          Thread thread1=new Thread(new printerText());
          Thread thread2=new Thread(new printerWord());

          thread2.start();
          thread1.start();
    }

    static  class  printerText implements Runnable  {

        @Override
        public void run() {
            for (int i = 1; i <=maxText; i++) {
                try {
                    if (isWord){
                        System.out.println(i);
                        continue;
                    }
                    text.acquire();
                    System.out.println(i);
                    word.release();
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            isText=true;
            text.release();
        }
    }
    static  class  printerWord implements  Runnable{
        @Override
        public void run() {
            for (int i = 'A'; i <=maxWord ; i++) {
               try {
                   //会一直等待这个信号量
                   if (isText){
                       System.out.println(i);
                       continue;
                   }
                   word.acquire();
                   System.out.println((char)i);
                   text.release();
               }catch (InterruptedException e){
                   e.printStackTrace();
               }
            }
            isWord=true;
            word.release();
        }
    }
}
